package com.ruoyi.customerPool.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.exception.base.BaseException;
import com.ruoyi.common.helper.LoginHelper;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.customer.common.DisCustomerBo;
import com.ruoyi.customer.common.DisCustomerRequestBo;
import com.ruoyi.customer.common.DisVo;
import com.ruoyi.customer.domain.Customer;
import com.ruoyi.customer.domain.bo.CustomerPoolPullBo;
import com.ruoyi.customer.domain.vo.CustomerImportVo;
import com.ruoyi.customer.domain.vo.CustomerVo;
import com.ruoyi.customer.mapper.CustomerMapper;
import com.ruoyi.customer.mapper.TmpCustomerMapper;
import com.ruoyi.customer.mapper.TotalComsterMapper;
import com.ruoyi.customer.service.DisCommonService;
import com.ruoyi.customerPool.domain.bo.CustomerPoolBo;
import com.ruoyi.customerPool.domain.bo.CustomerReturn;
import com.ruoyi.customerPool.domain.bo.DeptBo;
import com.ruoyi.customerPool.domain.bo.UserBo;
import com.ruoyi.customerPool.domain.vo.CustomerPoolVo;
import com.ruoyi.customerPool.domain.vo.UserVo;
import com.ruoyi.customerPool.mapper.CustomerPoolMapper;
import com.ruoyi.customerPool.service.ICustomerPoolService;
import com.ruoyi.disCustomer.domain.TCustomerDisRecord;
import com.ruoyi.disCustomer.mapper.TCustomerDisRecordMapper;
import com.ruoyi.enums.BusTypeEnum;
import com.ruoyi.enums.CompanyStatusEnum;
import com.ruoyi.enums.CustomerSort;
import com.ruoyi.returnCustomer.domain.TCustomerReturnRecord;
import com.ruoyi.returnCustomer.mapper.TCustomerReturnRecordMapper;
import com.ruoyi.system.mapper.SysDeptMapper;
import com.ruoyi.system.service.ISysConfigService;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

@RequiredArgsConstructor
@Service
public class CustomerPoolServiceImpl implements ICustomerPoolService {

    private final CustomerPoolMapper customerPoolMapper;
    private final SysDeptMapper deptMapper;
    private final CustomerMapper customerMapper;
    private final ISysConfigService configService;
    private final TmpCustomerMapper tmpCustomerMapper;
    private final TCustomerDisRecordMapper disRecordMapper;
    private final TCustomerReturnRecordMapper returnRecordMapper;
    private final TotalComsterMapper totalComsterMapper;
    private final DisCommonService disCommonService;


    /**
     * 客户池
     *
     * @param bo
     * @param pageQuery
     * @return
     */
    @Override
    public TableDataInfo<CustomerPoolVo> queryPageCustomerPoolList(CustomerPoolBo bo, PageQuery pageQuery) {
        // 从当前登录人获取child信息
        Page<CustomerPoolVo> result = customerPoolMapper.selectCustomerPool(pageQuery.build(), this.customerBuild(bo));
        return TableDataInfo.build(result.setRecords(regionBz(result, "1")));
    }

    private QueryWrapper<CustomerPoolVo> customerBuild(CustomerPoolBo bo) {
        QueryWrapper<CustomerPoolVo> mwq = Wrappers.query();
        mwq.eq("tc.task_id", -1);
        mwq.apply("tc.distribute_dept_id = d.dept_id");
        mwq.eq("tc.deleted", "0");
        mwq.eq("d.del_flag", "0");
        if (!LoginHelper.isAdmin(LoginHelper.getUserId())) {
            mwq.apply(
                    "( d.ancestors like '" + LoginHelper.getLoginUser().getChildren() + "%'" + " OR " + " d.dept_id = "
                            + LoginHelper.getDeptId() + " )");
        }
        // 处理搜索条件
        mwq.like(StringUtils.isNotBlank(bo.getName()), "tc.name", bo.getName())
                .eq(StringUtils.isNotBlank(bo.getTel()), "tc.tel", bo.getTel())
                .eq(StringUtils.isNotBlank(bo.getCustomerStatus()), "tc.customer_status", bo.getCustomerStatus())
                .eq(StringUtils.isNotBlank(bo.getLevel()), "tc.level", bo.getLevel())
                .eq(StringUtils.isNotBlank(bo.getLoanType()), "tc.loan_type", bo.getLoanType());

        mwq.eq(StringUtils.isNotBlank(bo.getCompanyStatus()), "tc.company_status", bo.getCompanyStatus());

        // 批次号
        mwq.like(StringUtils.isNotBlank(bo.getBatchLogo()), "tc.batch_logo", bo.getBatchLogo());

        // 未更新天数
        if (StringUtils.isNotBlank(bo.getNotUpdateDay())) {
            mwq.apply("TIMESTAMPDIFF(MINUTE, ifnull(tc.last_remark_time,'2000-12-31 00:00:00'), now()) >"
                    + bo.getNotUpdateDay() + " * 24 * 60");
        }
        // 1、进系统时间 2、实际申请时间
        if (StringUtils.isNotBlank(bo.getTimeType()) && StringUtils.isNotBlank(bo.getApplyTimeScope())) {
            String dateStr = "";
            // 今天、昨天、最近7天
            if (Arrays.asList("0", "1", "7").contains(bo.getApplyTimeScope())) {
                dateStr = DateUtils.getTimeBeforeDay(DateUtils.getNowDate(),
                        Integer.parseInt(bo.getApplyTimeScope()), "before");
            }
            // 本月
            if (Objects.equals("30", bo.getApplyTimeScope())) {
                dateStr = DateUtils.getFirstDayOfMonth();
            }
            if (StringUtils.isNotBlank(dateStr)) {
                if (Objects.equals("1", bo.getTimeType())) {
                    if (Arrays.asList("0", "1").contains(bo.getApplyTimeScope())) {
                        mwq.apply("tc.create_time = DATE_FORMAT('" + dateStr + "', '%Y-%m-%d 00:00:00' )");
                    } else {
                        mwq.apply("tc.create_time >= DATE_FORMAT('" + dateStr + "', '%Y-%m-%d 00:00:00' )");
                    }
                }
                if (Objects.equals("2", bo.getTimeType())) {
                    if (Arrays.asList("0", "1").contains(bo.getApplyTimeScope())) {
                        mwq.apply("tc.reality_apply_time = DATE_FORMAT('" + dateStr + "', '%Y-%m-%d 00:00:00' )");
                    } else {
                        mwq.apply("tc.reality_apply_time >= DATE_FORMAT('" + dateStr + "', '%Y-%m-%d 00:00:00' )");
                    }
                }
                mwq.apply(Objects.equals("2", bo.getTimeType()),
                        "tc.reality_apply_time >= DATE_FORMAT('" + dateStr + "', '%Y-%m-%d 00:00:00' )");
            }
            // 自定义时间特殊处理
            if (Objects.equals("99", bo.getApplyTimeScope())) {
                if (Objects.equals("1", bo.getTimeType())) {
                    mwq.ge(bo.getStartTime() != null, "tc.create_time", bo.getStartTime());
                    mwq.le(bo.getEndTime() != null, "tc.create_time", bo.getStartTime());
                } else {
                    mwq.ge(bo.getStartTime() != null, "tc.reality_apply_time", bo.getStartTime());
                    mwq.le(bo.getEndTime() != null, "tc.reality_apply_time", bo.getStartTime());
                }
            }
        }
        mwq.eq(bo.getDeptId() != null, "tc.distribute_dept_id", bo.getDeptId());

        mwq.eq(StringUtils.isNotBlank(bo.getVip()), "tc.vip", bo.getVip());
        // 房产
        mwq.eq(StringUtils.isNotBlank(bo.getHouse()), "tc.house", bo.getHouse());
        // 公积金
        mwq.eq(StringUtils.isNotBlank(bo.getFund()), "tc.fund", bo.getFund());
        // 备注查询
        mwq.like(StringUtils.isNotBlank(bo.getBz()), "tc.bz", bo.getBz());
        mwq.like(StringUtils.isNotBlank(bo.getEducation()), "tc.education", bo.getEducation());
        // 来源
        mwq.like(StringUtils.isNotBlank(bo.getSource()), "tc.source", bo.getSource());
        // 贷款额度
        String applyMoney = bo.getApplyMoney();
        if (StringUtils.isNotBlank(applyMoney)) {
            String[] split = applyMoney.split("-");
            if (split.length == 2) {
                // 需处理数据格式
                mwq.gt(StringUtils.isNotBlank(applyMoney), "tc.apply_money", Long.valueOf(split[0]));
                mwq.lt(StringUtils.isNotBlank(applyMoney), "tc.apply_money", Long.valueOf(split[1]));
            }
        }

        // 再审件
        if (Objects.equals("1", bo.getRevieweFlag())) {
            mwq.ne("tc.is_reviewe", -1);
        } else if (Objects.equals("0", bo.getRevieweFlag())) {
            mwq.eq("tc.is_reviewe", -1);
        }

        // 渠道id
        String channelId = bo.getChannelId();
        if (StringUtils.isNotBlank(channelId)) {
            channelId = "," + channelId + ",";
            mwq.like("tc.channel_ids", channelId);
        }

        mwq.last(StringUtils.isNotBlank(bo.getSortInfo()),
                "order by tc." + CustomerSort.of(bo.getSortInfo()) + " " + bo.getSortRule());

        if (!StringUtils.isNotBlank(bo.getSortInfo())) {
            mwq.orderByDesc("tc.id");
        }

        return mwq;
    }

    @Override
    public TableDataInfo<CustomerPoolVo> queryPageSameLevelPoolList(CustomerPoolBo bo, PageQuery pageQuery) {
        Page<CustomerPoolVo> result = customerPoolMapper.selectPageSameLevelPoolList(pageQuery.build(),
                this.buildSameQueryWrapper(bo));
        return TableDataInfo.build(result.setRecords(regionBz(result, "1")));
    }

    private List<CustomerPoolVo> regionBz(Page<CustomerPoolVo> result, String type) {
        return result.getRecords().stream().peek(customerVo -> {

            if (Objects.equals(type, "2")) {
                String tel = customerVo.getTel();
                if (StringUtils.isNotBlank(tel)) {
                    String resultTel = tel.replaceAll("(\\d{3})\\d{4}(\\d{4})", "$1****$2");
                    customerVo.setTel(resultTel);
                }
            }
        }).collect(Collectors.toList());
    }


    private QueryWrapper<CustomerPoolVo> buildSameQueryWrapper(CustomerPoolBo bo) {
        QueryWrapper<CustomerPoolVo> mwq = Wrappers.query();
        Long deptId = LoginHelper.getDeptId();
        mwq.eq("tc.deleted", 0);
        // 超级管理员
        if (!LoginHelper.isAdmin(LoginHelper.getUserId())) {
            mwq.eq("tc.distribute_dept_id", deptId);
        }
        // 处理搜索条件
        mwq.like(StringUtils.isNotBlank(bo.getName()), "tc.name", bo.getName())
                .eq(StringUtils.isNotBlank(bo.getTel()), "tc.tel", bo.getTel())
                .eq(StringUtils.isNotBlank(bo.getCustomerStatus()), "tc.customer_status", bo.getCustomerStatus())
                .eq(StringUtils.isNotBlank(bo.getLevel()), "tc.level", bo.getLevel())
                .eq(StringUtils.isNotBlank(bo.getLoanType()), "tc.loan_type", bo.getLoanType());

        mwq.eq(StringUtils.isNotBlank(bo.getCompanyStatus()), "tc.company_status", bo.getCompanyStatus());

        // 未更新天数
        if (StringUtils.isNotBlank(bo.getNotUpdateDay())) {
            mwq.apply("DATEDIFF( now(), IFNULL(tc.last_remark_time,'2000-12-31') ) >" + bo.getNotUpdateDay());
        }
        // 1、进系统时间 2、实际申请时间
        if (StringUtils.isNotBlank(bo.getTimeType()) && StringUtils.isNotBlank(bo.getApplyTimeScope())) {
            String dateStr = "";
            // 今天、昨天、最近7天
            if (Arrays.asList("0", "1", "7").contains(bo.getApplyTimeScope())) {
                dateStr = DateUtils.getTimeBeforeDay(DateUtils.getNowDate(),
                        Integer.parseInt(bo.getApplyTimeScope()), "before");
            }
            // 本月
            if (Objects.equals("30", bo.getApplyTimeScope())) {
                dateStr = DateUtils.getFirstDayOfMonth();
            }
            if (StringUtils.isNotBlank(dateStr)) {
                if (Objects.equals("1", bo.getTimeType())) {
                    if (Arrays.asList("0", "1").contains(bo.getApplyTimeScope())) {
                        mwq.apply("tc.create_time = DATE_FORMAT('" + dateStr + "', '%Y-%m-%d 00:00:00' )");
                    } else {
                        mwq.apply("tc.create_time >= DATE_FORMAT('" + dateStr + "', '%Y-%m-%d 00:00:00' )");
                    }
                }
                if (Objects.equals("2", bo.getTimeType())) {
                    if (Arrays.asList("0", "1").contains(bo.getApplyTimeScope())) {
                        mwq.apply("tc.reality_apply_time = DATE_FORMAT('" + dateStr + "', '%Y-%m-%d 00:00:00' )");
                    } else {
                        mwq.apply("tc.reality_apply_time >= DATE_FORMAT('" + dateStr + "', '%Y-%m-%d 00:00:00' )");
                    }
                }
                mwq.apply(Objects.equals("2", bo.getTimeType()),
                        "tc.reality_apply_time >= DATE_FORMAT('" + dateStr + "', '%Y-%m-%d 00:00:00' )");
            }
            // 自定义时间特殊处理
            if (Objects.equals("99", bo.getApplyTimeScope())) {
                if (Objects.equals("1", bo.getTimeType())) {
                    mwq.ge(bo.getStartTime() != null, "tc.create_time", bo.getStartTime());
                    mwq.le(bo.getEndTime() != null, "tc.create_time", bo.getStartTime());
                } else {
                    mwq.ge(bo.getStartTime() != null, "tc.reality_apply_time", bo.getStartTime());
                    mwq.le(bo.getEndTime() != null, "tc.reality_apply_time", bo.getStartTime());
                }
            }
        }
        mwq.eq(bo.getDeptId() != null, "tc.distribute_dept_id", bo.getDeptId());

        mwq.eq(StringUtils.isNotBlank(bo.getVip()), "tc.vip", bo.getVip());
        // 房产
        mwq.eq(StringUtils.isNotBlank(bo.getHouse()), "tc.house", bo.getHouse());
        // 公积金
        mwq.eq(StringUtils.isNotBlank(bo.getFund()), "tc.fund", bo.getFund());
        // 备注查询
        mwq.like(StringUtils.isNotBlank(bo.getBz()), "tc.bz", bo.getBz());
        mwq.like(StringUtils.isNotBlank(bo.getEducation()), "tc.education", bo.getEducation());
        // 来源
        mwq.like(StringUtils.isNotBlank(bo.getSource()), "tc.source", bo.getSource());
        // 贷款额度
        String applyMoney = bo.getApplyMoney();
        if (StringUtils.isNotBlank(applyMoney)) {
            String[] split = applyMoney.split("-");
            if (split.length == 2) {
                // 需处理数据格式
                mwq.gt(StringUtils.isNotBlank(applyMoney), "tc.apply_money", Long.valueOf(split[0]));
                mwq.lt(StringUtils.isNotBlank(applyMoney), "tc.apply_money", Long.valueOf(split[1]));
            }
        }

        // 再审件
        if (Objects.equals("1", bo.getRevieweFlag())) {
            mwq.ne("tc.is_reviewe", -1);
        } else if (Objects.equals("0", bo.getRevieweFlag())) {
            mwq.eq("tc.is_reviewe", -1);
        }
        mwq.eq("tc.task_id", -1);
        mwq.orderByDesc("tc.create_time");
        return mwq;
    }


    @Override
    public TableDataInfo<CustomerPoolVo> queryPageLowerLevelPoolList(CustomerPoolBo bo, PageQuery pageQuery) {
        Page<CustomerPoolVo> result = customerPoolMapper.selectPageLowerLevelPoolList(pageQuery.build(),
                this.buildLowerQueryWrapper(bo));
        return TableDataInfo.build(result.setRecords(regionBz(result, "1")));
    }

    @Override
    public TableDataInfo<CustomerPoolVo> querySuperiorCustomerList(CustomerPoolBo bo, PageQuery pageQuery) {
        // 上级客户
        Page<CustomerPoolVo> result = customerPoolMapper.querySuperiorCustomerList(pageQuery.build(),
                this.querySuperiorCustomer(bo));
        return TableDataInfo.build(result.setRecords(regionBz(result, "2")));
    }

    private QueryWrapper<CustomerPoolVo> querySuperiorCustomer(CustomerPoolBo bo) {
        QueryWrapper<CustomerPoolVo> mwq = Wrappers.query();
        mwq.eq("tc.task_id", -1);
        mwq.apply("tc.distribute_dept_id = d.dept_id");
        mwq.eq("tc.deleted", "0");
        mwq.eq("d.del_flag", "0");
        if (!LoginHelper.isAdmin(LoginHelper.getUserId())) {
            mwq.apply(
                    "( d.ancestors like '" + LoginHelper.getLoginUser().getChildren() + "%'" + " OR " + " d.dept_id = "
                            + LoginHelper.getDeptId() + " )");
        }
        // 处理搜索条件
        mwq.like(StringUtils.isNotBlank(bo.getName()), "tc.name", bo.getName())
                .eq(StringUtils.isNotBlank(bo.getTel()), "tc.tel", bo.getTel())
                .eq(StringUtils.isNotBlank(bo.getCustomerStatus()), "tc.customer_status", bo.getCustomerStatus())
                .eq(StringUtils.isNotBlank(bo.getLevel()), "tc.level", bo.getLevel())
                .eq(StringUtils.isNotBlank(bo.getLoanType()), "tc.loan_type", bo.getLoanType());

        mwq.eq(StringUtils.isNotBlank(bo.getCompanyStatus()), "tc.company_status", bo.getCompanyStatus());

        // 未更新天数
        if (StringUtils.isNotBlank(bo.getNotUpdateDay())) {
            mwq.apply("DATEDIFF( now(), IFNULL(tc.last_remark_time,'2000-12-31') ) >" + bo.getNotUpdateDay());
        }
        // 1、进系统时间 2、实际申请时间
        if (StringUtils.isNotBlank(bo.getTimeType()) && StringUtils.isNotBlank(bo.getApplyTimeScope())) {
            String dateStr = "";
            // 今天、昨天、最近7天
            if (Arrays.asList("0", "1", "7").contains(bo.getApplyTimeScope())) {
                dateStr = DateUtils.getTimeBeforeDay(DateUtils.getNowDate(),
                        Integer.parseInt(bo.getApplyTimeScope()), "before");
            }
            // 本月
            if (Objects.equals("30", bo.getApplyTimeScope())) {
                dateStr = DateUtils.getFirstDayOfMonth();
            }
            if (StringUtils.isNotBlank(dateStr)) {
                if (Objects.equals("1", bo.getTimeType())) {
                    if (Arrays.asList("0", "1").contains(bo.getApplyTimeScope())) {
                        mwq.apply("tc.create_time = DATE_FORMAT('" + dateStr + "', '%Y-%m-%d 00:00:00' )");
                    } else {
                        mwq.apply("tc.create_time >= DATE_FORMAT('" + dateStr + "', '%Y-%m-%d 00:00:00' )");
                    }
                }
                if (Objects.equals("2", bo.getTimeType())) {
                    if (Arrays.asList("0", "1").contains(bo.getApplyTimeScope())) {
                        mwq.apply("tc.reality_apply_time = DATE_FORMAT('" + dateStr + "', '%Y-%m-%d 00:00:00' )");
                    } else {
                        mwq.apply("tc.reality_apply_time >= DATE_FORMAT('" + dateStr + "', '%Y-%m-%d 00:00:00' )");
                    }
                }
                mwq.apply(Objects.equals("2", bo.getTimeType()),
                        "tc.reality_apply_time >= DATE_FORMAT('" + dateStr + "', '%Y-%m-%d 00:00:00' )");
            }
            // 自定义时间特殊处理
            if (Objects.equals("99", bo.getApplyTimeScope())) {
                if (Objects.equals("1", bo.getTimeType())) {
                    mwq.ge(bo.getStartTime() != null, "tc.create_time", bo.getStartTime());
                    mwq.le(bo.getEndTime() != null, "tc.create_time", bo.getStartTime());
                } else {
                    mwq.ge(bo.getStartTime() != null, "tc.reality_apply_time", bo.getStartTime());
                    mwq.le(bo.getEndTime() != null, "tc.reality_apply_time", bo.getStartTime());
                }
            }
        }
        mwq.eq(bo.getDeptId() != null, "tc.distribute_dept_id", bo.getDeptId());

        mwq.eq(StringUtils.isNotBlank(bo.getVip()), "tc.vip", bo.getVip());
        // 房产
        mwq.eq(StringUtils.isNotBlank(bo.getHouse()), "tc.house", bo.getHouse());
        // 公积金
        mwq.eq(StringUtils.isNotBlank(bo.getFund()), "tc.fund", bo.getFund());
        // 备注查询
        mwq.like(StringUtils.isNotBlank(bo.getBz()), "tc.bz", bo.getBz());
        mwq.like(StringUtils.isNotBlank(bo.getEducation()), "tc.education", bo.getEducation());
        // 来源
        mwq.like(StringUtils.isNotBlank(bo.getSource()), "tc.source", bo.getSource());
        // 贷款额度
        String applyMoney = bo.getApplyMoney();
        if (StringUtils.isNotBlank(applyMoney)) {
            String[] split = applyMoney.split("-");
            if (split.length == 2) {
                // 需处理数据格式
                mwq.gt(StringUtils.isNotBlank(applyMoney), "tc.apply_money", Long.valueOf(split[0]));
                mwq.lt(StringUtils.isNotBlank(applyMoney), "tc.apply_money", Long.valueOf(split[1]));
            }
        }

        // 再审件
        if (Objects.equals("1", bo.getRevieweFlag())) {
            mwq.ne("tc.is_reviewe", -1);
        } else if (Objects.equals("0", bo.getRevieweFlag())) {
            mwq.eq("tc.is_reviewe", -1);
        }
        mwq.orderByDesc("tc.id");

        return mwq;
    }

    /**
     * 查找当前登录人部门下的 角色为salesman的用户
     *
     * @param userBo
     * @return
     */
    @Override
    public List<UserVo> getUsrList(UserBo userBo) {
        return customerPoolMapper.getUserList(this.getUserList(userBo));
    }

    @Override
    public List<SysDept> getDeptList(DeptBo deptBo) {
        // 获取当前登录人的查询信息 下级部门信息
        String children = LoginHelper.getLoginUser().getChildren();
        QueryWrapper<SysDept> query = Wrappers.query();
        // 类型为2 包含当前自己部门
        String type = deptBo.getType();
        query.apply("del_flag = 0 and status = 0");
        query.apply("( ancestors like concat('" + children + "', '%')" + (Objects.equals("2", type) ? (" OR dept_id = " + LoginHelper.getDeptId()) : "") + " )");
        query.orderByAsc("dept_id");
        return customerPoolMapper.selectDeptList(query);

    }

    @Override
    public List<SysDept> getDeptInfoList(SysDept sysDept) {
        LambdaQueryWrapper<SysDept> sysDeptLambdaQueryWrapper = new LambdaQueryWrapper<>();
        sysDeptLambdaQueryWrapper.eq(SysDept::getDelFlag, "0");
        if (Objects.nonNull(sysDept.getParentId())) {
            sysDeptLambdaQueryWrapper.eq(SysDept::getParentId, sysDept.getParentId());
        }
        return deptMapper.selectDeptList(sysDeptLambdaQueryWrapper);
    }


    @Override
    @Transactional
    public void allotCustomerToDept(DisCustomerRequestBo requestBo) {
        List<DisCustomerBo> customerBos = disCommonService.checkDataDept(requestBo, BusTypeEnum.POLL.getCode());
        List<DisVo> disVos = disCommonService.dataDealDept(customerBos, requestBo.getDeptBos());
        disCommonService.disToDept(disVos, BusTypeEnum.POLL.getCode(), LoginHelper.getLoginUser().getNickName(), LoginHelper.getUserId(), LoginHelper.getDeptId());
    }

    /**
     * 记录分配记录
     *
     * @param disRecord
     */
    private void disRecord(TCustomerDisRecord disRecord) {
        disRecord.setOperateDisId(LoginHelper.getUserId());
        disRecord.setOperateDeptId(LoginHelper.getDeptId());
        disRecord.setOperateDisName(LoginHelper.getLoginUser().getNickName());
        disRecord.setCreateTime(DateUtils.getNowDate());
        disRecordMapper.insert(disRecord);
    }

    @Override
    public String downLoad() {
        // 更改为固定模板信息
        String localPath = RuoYiConfig.getProfile();
        String downloadPath = localPath + File.separator;
        String filename = "优质客户" + System.currentTimeMillis();
        FileOutputStream fs = null;
        FileInputStream fileInputStream = null;
        try {
            int byteread;
            fileInputStream = new FileInputStream(downloadPath + "优质客户表.xlsx");
            fs = new FileOutputStream(RuoYiConfig.getDownloadPath() + File.separator + filename + ".xlsx");
            byte[] buffer = new byte[1204];
            while ((byteread = fileInputStream.read(buffer)) != -1) {
                fs.write(buffer, 0, byteread);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (fs != null) {
                    fs.close();
                }
                if (fileInputStream != null) {
                    fileInputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return filename + ".xlsx";
    }

    /**
     * 分配到用户
     */
    @Override
    @Transactional
    public void allotCustomerToUser(DisCustomerRequestBo requestBo) {
        List<DisCustomerBo> customerBos = disCommonService.checkDataUser(requestBo, BusTypeEnum.POLL.getCode());
        List<DisVo> disVos = disCommonService.dataDealUser(customerBos, requestBo.getUserBos());

        //Map<String, Object> map = disCommonService.userDataDeal(disVos);
       // List<DisVo> successList = (List<DisVo>) map.get("success");
        disCommonService.disToUser(disVos, BusTypeEnum.POLL.getCode(), LoginHelper.getLoginUser().getNickName(), LoginHelper.getUserId(), LoginHelper.getDeptId());

        //disCommonService.sentInfo(Constants.DIS_MESSAGE, map);
    }


    /**
     * 客户池退回
     *
     * @param customerReturn
     */
    @Override
    @Transactional
    public void returnCustomer(CustomerReturn customerReturn) {
        List<CustomerPoolBo> customers = customerReturn.getCustomers();
        if (!CollectionUtils.isEmpty(customers)) {
            for (CustomerPoolBo customerPoolBo : customers) {
                Long customerId = customerPoolBo.getId();
                // 判断是否存在在审件信息(customerStatus为已签约)
                CustomerVo customerVo = Optional.ofNullable(customerMapper.selectVoById(customerId))
                        .orElseThrow(() -> new ServiceException("客户信息不存在"));
                if (Objects.equals(customerVo.getDeleted(), "1")) {
                    throw new ServiceException("客户已经不存在");
                }
                if (customerVo.getIsReviewe() != -1) {
                    continue;
                }
                // 客户状态为新数据
//                if (!Objects.equals(customerVo.getCustomerStatus(), CustomerStatusEnum.XSJ.getCode())) {
//                    continue;
//                }
                // 退回客户到上一级
                SysDept sysDept = Optional.ofNullable(deptMapper.selectVoById(customerPoolBo.getDeptId()))
                        .orElseThrow(() -> new BaseException("客户信息没有找到"));
                Long parentId = sysDept.getParentId();
                Customer customer = new Customer();
                customer.setId(customerPoolBo.getId());
                customer.setDistributeDeptId(parentId == 0 ? customerPoolBo.getDeptId() : parentId);
                //customer.setCompanyStatus(CompanyStatusEnum.DFP.getCode());
                // 更改为已退回
                customer.setCompanyStatus(CompanyStatusEnum.YTH.getCode());
                customerMapper.updateById(customer);

                // 保存退回记录
                TCustomerReturnRecord returnRecord = new TCustomerReturnRecord();
                returnRecord.setBusType(BusTypeEnum.POLL.getCode());
                returnRecord.setCustomerId(customerId);
                // 分配给哪个用户
                returnRecord.setReturnDeptId(parentId);
                returnRecord.setCustomerName(customerVo.getName());
                returnRecord.setTel(customerVo.getTel());
                returnRecord.setReturnReason(customerReturn.getBackReason());
                saveReturnRecord(returnRecord);
            }
        }
    }

    private void saveReturnRecord(TCustomerReturnRecord returnRecord) {
        returnRecord.setOperatorId(LoginHelper.getUserId());
        returnRecord.setOperatorDeptId(LoginHelper.getDeptId());
        returnRecord.setOperatorName(LoginHelper.getLoginUser().getNickName());
        returnRecord.setCreateTime(DateUtils.getNowDate());
        returnRecordMapper.insert(returnRecord);
    }

    @Override
    @Transactional
    public void deptPoolPull(CustomerPoolPullBo customerReturn) {
        String type = customerReturn.getType();
        if (!"deptPull".equals(type)) {
            throw new BaseException("参数异常");
        }
        List<CustomerPoolVo> customerPoolVos = customerReturn.getCustomerPoolVos();
        if (!CollectionUtils.isEmpty(customerPoolVos)) {
            for (CustomerPoolVo customerPoolVo : customerPoolVos) {
                Long customerId = customerPoolVo.getId();
                // 判断是否存在在审件信息(customerStatus为已签约)
                CustomerVo customerVo = Optional.ofNullable(customerMapper.selectVoById(customerId))
                        .orElseThrow(() -> new ServiceException("客户信息不存在"));
                if (Objects.equals(customerVo.getDeleted(), "1")) {
                    throw new ServiceException("客户已经不存在");
                }
                if (customerVo.getIsReviewe() != -1) {
                    continue;
                }
                // 客户状态为新数据
//                if (!Objects.equals(customerVo.getCustomerStatus(), CustomerStatusEnum.XSJ.getCode())) {
//                    continue;
//                }
                Customer customer = new Customer();
                customer.setDistributeDeptId(LoginHelper.getDeptId());
                customer.setId(customerPoolVo.getId());
                customer.setCompanyStatus(CompanyStatusEnum.YXF.getCode());
                customerMapper.updateById(customer);

                TCustomerDisRecord disRecord = new TCustomerDisRecord();
                disRecord.setBusType(BusTypeEnum.DEPT_PULL.getCode());
                disRecord.setCustomerId(customerId);
                // 分配给哪个部门
                disRecord.setDisDeptId(LoginHelper.getDeptId());
                disRecord.setCustomerName(customerVo.getName());
                disRecord.setTel(customerVo.getTel());
                // 记录分配记录
                disRecord(disRecord);
            }
        }
    }


    @Override
    @Transactional
    public String importCustomerData(List<CustomerImportVo> customerImportVos) {
        // 数据保存到临时表
        Long userId = LoginHelper.getUserId();
        String dateToStr = DateUtils.parseDateToStr(DateUtils.YYYYMMDDHHMMSS, DateUtils.getNowDate());
        String tableName = "import_customer_" + dateToStr + userId;
        export(customerImportVos, tableName);

        // 客户表去重
        tmpCustomerMapper.customerDeWeight(tableName);
        // 写入客户表
        tmpCustomerMapper.insertTmpToCustomer(tableName);

        List<CustomerImportVo> customerImportVos1 = tmpCustomerMapper.importDataErrMsg(tableName);
        if (!CollectionUtils.isEmpty(customerImportVos1)) {
            return customerImportVos1.stream().map(it -> {
                return "手机号：" + it.getTel() + "（" + it.getErrMsg() + "）";
            }).collect(Collectors.joining("<br>"));
        }
        return "成功导入";
    }

    /**
     * 导入临时表
     *
     * @param customerImportVos
     * @return java.lang.String
     * @author: suntf
     * @date: 2023/8/23 13:52
     */
    @Transactional(rollbackFor = Exception.class)
    public void export(List<CustomerImportVo> customerImportVos, String tableName) {
        tmpCustomerMapper.createTmpCustomer(tableName);
        for (CustomerImportVo customerImportVo : customerImportVos) {
            // 手机号为空 不保存数据
            if (!StringUtils.isNotBlank(customerImportVo.getTel())) {
                continue;
            }
            // 手机号去除空格
            customerImportVo.setTel(customerImportVo.getTel().trim());
            customerImportVo.setUserId(LoginHelper.getUserId());
            customerImportVo.setDeptId(LoginHelper.getDeptId());
            customerImportVo.setCreateBy(LoginHelper.getLoginUser().getNickName());
            tmpCustomerMapper.insertTmpCustomer(customerImportVo, tableName);
        }
        // 验证手机号码是否合法 手机号不正规 暂不校验
        //tmpCustomerMapper.checkMobileRight(tableName);
        // 本身去重
        tmpCustomerMapper.bsDeWeight(tableName);
    }

    /**
     * 导入总表
     *
     * @param customerImportVos
     * @param tableName
     * @param batchLogo
     * @return void
     * @author: suntf
     * @date: 2023/8/23 14:50
     */
    @Transactional(rollbackFor = Exception.class)
    public void exportTotalCustom(List<CustomerImportVo> customerImportVos, String tableName, String batchLogo) {
        export(customerImportVos, tableName);
        //和总表验证是否重复
        tmpCustomerMapper.checkTelRepeat(tableName);
        // 验证存在的手机号码再哪里
        // 客户表去重
        tmpCustomerMapper.customerDeWeight(tableName);
        tmpCustomerMapper.updateUser(tableName);
        // 导入总表中
        String date = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, DateUtils.getNowDate());
        tmpCustomerMapper.importTotalCustomer(tableName, date, batchLogo);
    }

    /**
     * 批量退回总池子
     *
     * @param customers
     * @return com.ruoyi.common.core.domain.R
     * @author: suntf
     * @date: 2023/8/28 18:44
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public R bathReturnTotalCutomer(Customer customers) {
        if (CollectionUtils.isEmpty(customers.getIds())) {
            return R.fail("请选择客户信息");
        }
        customers.getIds().forEach(item -> {
            // 更新客户信息
            totalComsterMapper.updateCustomerStatus(item, customers.getRemark(),
                    LoginHelper.getLoginUser().getNickName());

            // 记录退回记录

            CustomerVo customerVo = customerMapper.selectVoById(item);
            if (customerVo != null) {
                // 记录退回信息
                TCustomerReturnRecord returnRecord = new TCustomerReturnRecord();
                returnRecord.setBusType(BusTypeEnum.POLL.getCode());
                returnRecord.setCustomerId(item);

                returnRecord.setCustomerName(customerVo.getName());
                returnRecord.setTel(customerVo.getTel());
                returnRecord.setReturnReason(customers.getRemark());
                returnRecord.setOperatorId(LoginHelper.getUserId());
                returnRecord.setOperatorDeptId(LoginHelper.getDeptId());
                returnRecord.setOperatorName(LoginHelper.getLoginUser().getNickName());
                returnRecord.setCreateTime(DateUtils.getNowDate());
                returnRecordMapper.insert(returnRecord);
            }
        });
        return R.ok();
    }

    private QueryWrapper<SysUser> getUserList(UserBo user) {
        String children = LoginHelper.getLoginUser().getChildren();
        String ancestors = LoginHelper.getLoginUser().getAncestors();
        QueryWrapper<SysUser> query = Wrappers.query();
        query.apply("u.del_flag = " + UserConstants.USER_NORMAL + " and u.user_id <> 1");
        //query.apply("u.dept_id = d.dept_id and  u.user_id = sur.user_id and r.role_id = sur.role_id");
        String key = configService.selectConfigByKey(Constants.SALESMAN_ROLEKEY_TYPE);
        query.apply("r.role_key in (" + key + ")");
        query.apply(
                "(d.ancestors like concat('" + children + "', '%') or u.dept_id = " + LoginHelper.getDeptId() + ")");
        query.orderByAsc("u.user_id");
        return query;
    }

    private QueryWrapper<CustomerPoolVo> buildLowerQueryWrapper(CustomerPoolBo bo) {
        QueryWrapper<CustomerPoolVo> mwq = Wrappers.query();
        mwq.eq("tc.deleted", "0");
        Long deptId = LoginHelper.getDeptId();
        // 不为超级管理员
        if (!LoginHelper.isAdmin(LoginHelper.getUserId())) {
            // 根据当前部门id查询下面的部门id
            List<String> deptList = customerPoolMapper.lowerDept(deptId);
            mwq.in(!CollectionUtils.isEmpty(deptList), "tc.distribute_dept_id", deptList);
            mwq.eq(CollectionUtils.isEmpty(deptList), "tc.distribute_dept_id", -2);
        }
        mwq.like(StringUtils.isNotBlank(bo.getName()), "tc.name", bo.getName())
                .eq(StringUtils.isNotBlank(bo.getTel()), "tc.tel", bo.getTel())
                .eq(StringUtils.isNotBlank(bo.getLevel()), "tc.level", bo.getLevel())
                .eq(StringUtils.isNotBlank(bo.getLoanType()), "tc.loan_type", bo.getLoanType())
                .like(StringUtils.isNotBlank(bo.getEducation()), "tc.education", bo.getEducation())
                .eq(StringUtils.isNotBlank(bo.getHouse()), "tc.house", bo.getHouse())
                .eq(StringUtils.isNotBlank(bo.getCar()), "tc.car", bo.getCar())
                .eq(StringUtils.isNotBlank(bo.getWarranty()), "tc.warranty", bo.getWarranty())
                .eq(StringUtils.isNotBlank(bo.getInsurance()), "tc.insurance", bo.getInsurance())
                .eq(StringUtils.isNotBlank(bo.getFund()), "tc.fund", bo.getFund())
                .eq(StringUtils.isNotBlank(bo.getProvince()), "tc.province", bo.getProvince())
                .eq(StringUtils.isNotBlank(bo.getCity()), "tc.city", bo.getCity())
                .eq(StringUtils.isNotBlank(bo.getCounty()), "tc.county", bo.getCounty())
                .like(StringUtils.isNotBlank(bo.getManager()), "tc.manager", bo.getManager())
                .eq(StringUtils.isNotBlank(bo.getCustomerStatus()), "tc.customer_status", bo.getCustomerStatus());
        String applyMoney = bo.getApplyMoney();
        if (StringUtils.isNotBlank(applyMoney)) {
            String[] split = applyMoney.split("-");
            if (split.length == 2) {
                mwq.gt(StringUtils.isNotBlank(applyMoney), "tc.apply_money", split[0]);
                mwq.lt(StringUtils.isNotBlank(applyMoney), "tc.apply_money", split[1]);
            }
        }
        String age = bo.getAge();
        if (StringUtils.isNotBlank(age)) {
            String[] split = age.split("-");
            if (split.length == 2) {
                mwq.gt("tc.age", split[0]);
                mwq.lt("tc.age", split[1]);
            }
        }
        mwq.eq("tc.task_id", -1);
        mwq.orderByDesc("tc.create_time");
        return mwq;
    }
}
